package org.adream.account.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.springframework.util.StringUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码生成util
 * 
 * @author chenhaoyu
 *
 */
public class ZXingUtil {

	public static final String QRCODE_DEFAULT_CHARSET = "UTF-8";
	public static final int QRCODE_DEFAULT_WIDTH = 160;
	public static final int QRCODE_DEFAULT_HEIGHT = 160;
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

	public static BufferedImage getQRCode(String info) {
		return createQRCode(info, QRCODE_DEFAULT_CHARSET, QRCODE_DEFAULT_WIDTH, QRCODE_DEFAULT_HEIGHT);
	}

	public static BufferedImage getQRCode(String info, String charset) {
		return createQRCode(info, charset, QRCODE_DEFAULT_WIDTH, QRCODE_DEFAULT_HEIGHT);
	}
	
	public static BufferedImage getQRCode(String info,Integer width,Integer height) {
		return createQRCode(info, QRCODE_DEFAULT_CHARSET, width, height);
	}

	public static BufferedImage getQRCode(String info, String charset, Integer width, Integer height) {
		return createQRCode(info, charset, width, height);
	}
	private static BufferedImage createQRCode(String data, String charset, Integer width, Integer height) {
		BitMatrix matrix;
		Map<EncodeHintType, Comparable<?>> hint = new HashMap<EncodeHintType, Comparable<?>>();
		hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hint.put(EncodeHintType.CHARACTER_SET, charset);
		try {
			if(StringUtils.isEmpty(width) || width == Constant.ZERO) {
				width = QRCODE_DEFAULT_WIDTH;
			}
			if(StringUtils.isEmpty(height) || height == Constant.ZERO) {
				height = QRCODE_DEFAULT_HEIGHT;
			}
			matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE,
					width, height, hint);
			matrix = deleteWhite(matrix);
			return toBufferedImage(matrix);
		} catch (WriterException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 去出二维码白边太大，删除白边
	 * 
	 * @param matrix
	 * @return
	 */
	private static BitMatrix deleteWhite(BitMatrix matrix) {
		int[] rec = matrix.getEnclosingRectangle();
		int resWidth = rec[2] + 1;
		int resHeight = rec[3] + 1;

		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
		resMatrix.clear();
		for (int i = 0; i < resWidth; i++) {
			for (int j = 0; j < resHeight; j++) {
				if (matrix.get(i + rec[0], j + rec[1]))
					resMatrix.set(i, j);
			}
		}
		return resMatrix;
	}

	/**
	 * matrix 2 BufferedImage
	 * 
	 * @param matrix
	 * @return
	 */
	private static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
	
	
	
	public static String getLogoQRCode(String qrUrl, InputStream file, String productName, ServletOutputStream sops) throws Exception {
		String content = qrUrl;
		ZXingUtil zp = new ZXingUtil();
		BufferedImage bim = zp.getQR_CODEBufferedImage(content, BarcodeFormat.QR_CODE, 400, 400,
				zp.getDecodeHintType());
		return zp.addLogo_QRCode(bim, file, new LogoConfig(), productName, sops);
	}
	/**
	 * 给二维码图片添加Logo
	 * 
	 * @param qrPic
	 * @param logoPic
	 * @throws IOException 
	 */
	public String addLogo_QRCode(BufferedImage bim, InputStream logoPic, LogoConfig logoConfig, String productName, ServletOutputStream sops) throws Exception {
			/** * 读取二维码图片，并构建绘图对象 */
			BufferedImage image = bim;
			Graphics2D g = image.createGraphics();

			/** * 读取Logo图片 */
			BufferedImage logo = ImageIO.read(logoPic);
			/** * 设置logo的大小,本人设置为二维码图片的20%,因为过大会盖掉二维码 */
			int widthLogo = logo.getWidth(null) > image.getWidth() * 3 / 10 ? (image.getWidth() * 3 / 10)
					: logo.getWidth(null),
					heightLogo = logo.getHeight(null) > image.getHeight() * 3 / 10 ? (image.getHeight() * 3 / 10)
							: logo.getWidth(null);

			/** * logo放在中心 */
			int x = (image.getWidth() - widthLogo) / 2;
			int y = (image.getHeight() - heightLogo) / 2;
			/**
			 * * logo放在右下角 * int x = (image.getWidth() - widthLogo); * int y =
			 * (image.getHeight() - heightLogo);
			 */

			// 开始绘制图片
			g.drawImage(logo, x, y, widthLogo, heightLogo, null);
			// g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
			// g.setStroke(new BasicStroke(logoConfig.getBorder()));
			// g.setColor(logoConfig.getBorderColor());
			// g.drawRect(x, y, widthLogo, heightLogo);
			g.dispose();

			// 把商品名称添加上去，商品名称不要太长哦，这里最多支持两行。太长就会自动截取啦
			if (productName != null && !productName.equals("")) {
				// 新的图片，把带logo的二维码下面加上文字
				BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
				Graphics2D outg = outImage.createGraphics();
				// 画二维码到新的面板
				outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
				// 画文字到新的面板
				outg.setColor(Color.BLACK);
				outg.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
				int strWidth = outg.getFontMetrics().stringWidth(productName);
				if (strWidth > 399) {
					// //长度过长就截取前面部分
					// outg.drawString(productName, 0, image.getHeight() +
					// (outImage.getHeight() - image.getHeight())/2 + 5 ); //画文字
					// 长度过长就换行
					String productName1 = productName.substring(0, productName.length() / 2);
					String productName2 = productName.substring(productName.length() / 2, productName.length());
					int strWidth1 = outg.getFontMetrics().stringWidth(productName1);
					int strWidth2 = outg.getFontMetrics().stringWidth(productName2);
					outg.drawString(productName1, 200 - strWidth1 / 2,
							image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 + 12);
					BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
					Graphics2D outg2 = outImage2.createGraphics();
					outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
					outg2.setColor(Color.BLACK);
					outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
					outg2.drawString(productName2, 200 - strWidth2 / 2,
							outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
					outg2.dispose();
					outImage2.flush();
					outImage = outImage2;
				} else {
					outg.drawString(productName, 200 - strWidth / 2,
							image.getHeight() + (outImage.getHeight() - image.getHeight()) / 2 + 12); // 画文字
				}
				outg.dispose();
				outImage.flush();
				image = outImage;
			}
			logo.flush();
			image.flush();
			
			if(sops!=null){
				ImageIO.write(image, "png", sops);
				sops.flush();
				return "";
			}
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			baos.flush();
			ImageIO.write(image, "png", baos);

			String imageBase64QRCode = Base64.getEncoder().encodeToString(baos.toByteArray());
			baos.close();
			return imageBase64QRCode;
	}
	/** * 构建初始化二维码 * * @param bm * @return */
	public BufferedImage fileToBufferedImage(BitMatrix bm) {
		BufferedImage image = null;
		try {
			int w = bm.getWidth(), h = bm.getHeight();
			image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

			for (int x = 0; x < w; x++) {
				for (int y = 0; y < h; y++) {
					image.setRGB(x, y, bm.get(x, y) ? 0xFF000000 : 0xFFCCDDEE);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}

	/**
	 * * 生成二维码bufferedImage图片 * * @param content * 编码内容 * @param barcodeFormat *
	 * 编码类型 * @param width * 图片宽度 * @param height * 图片高度 * @param hints * 设置参数
	 * * @return
	 */
	public BufferedImage getQR_CODEBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height,
			Map<EncodeHintType, ?> hints) {
		MultiFormatWriter multiFormatWriter = null;
		BitMatrix bm = null;
		BufferedImage image = null;
		try {
			multiFormatWriter = new MultiFormatWriter();
			// 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
			bm = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);
			int w = bm.getWidth();
			int h = bm.getHeight();
			image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

			// 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
			for (int x = 0; x < w; x++) {
				for (int y = 0; y < h; y++) {
					image.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
				}
			}
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return image;
	}
	/** * 设置二维码的格式参数 * * @return */
	@SuppressWarnings("deprecation")
	public Map<EncodeHintType, Object> getDecodeHintType() {
		// 用于设置QR二维码参数
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		// 设置编码方式
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 0);
		hints.put(EncodeHintType.MAX_SIZE, 350);
		hints.put(EncodeHintType.MIN_SIZE, 100);

		return hints;
	}
}


class LogoConfig {
	// logo默认边框颜色
	public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
	// logo默认边框宽度
	public static final int DEFAULT_BORDER = 2;
	// logo大小默认为照片的1/5
	public static final int DEFAULT_LOGOPART = 5;

	private final int border = DEFAULT_BORDER;
	private final Color borderColor;
	private final int logoPart;

	/**
	 * * Creates a default config with on color {@link #BLACK} and off color *
	 * {@link #WHITE}, generating normal black-on-white barcodes.
	 */
	public LogoConfig() {
		this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
	}

	public LogoConfig(Color borderColor, int logoPart) {
		this.borderColor = borderColor;
		this.logoPart = logoPart;
	}

	public Color getBorderColor() {
		return borderColor;
	}

	public int getBorder() {
		return border;
	}

	public int getLogoPart() {
		return logoPart;
	}
}
